package com.itcast.com.itcast;

import com.aliyuncs.exceptions.ClientException;
import com.itcast.constant.MessageConstant;
import com.itcast.constant.RedisConstant;
import com.itcast.constant.RedisMessageConstant;
import com.itcast.entity.Result;
import com.itcast.utils.SMSUtils;
import com.itcast.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * 发送短信验证码
 */
@RestController
@RequestMapping("/vaildateCode")
public class VaildateCodeController {

    @Autowired
    private JedisPool jedisPool;
    @RequestMapping("/send")
    public Result sendVaildataCode(String telephone){
        String vaildateCode =null;
        if (telephone==null&&telephone.length()==0){
            return new Result(
            false,MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        vaildateCode = ValidateCodeUtils.
                generateValidateCode4String(6);
        jedisPool.getResource().setex(
                telephone+ RedisMessageConstant.
                 SENDTYPE_ORDER,60*60*5,vaildateCode);
            try {
                SMSUtils.sendShortMessage(
                        SMSUtils.VALIDATE_CODE,
                        telephone,vaildateCode);

                return new Result(true,
                        MessageConstant.SEND_VALIDATECODE_SUCCESS);
            } catch (ClientException e) {
                e.printStackTrace();
                return new Result(false,
                        MessageConstant.SEND_VALIDATECODE_FAIL);
            }


    }


    /**
     * 发送登录短信验证码
     * @param telephone
     * @return
     */
    @RequestMapping("/send4Login")
    public Result send4Login(String telephone){
        telephone = telephone.trim();
        if (telephone!=null&&telephone.length()>0){
            try {
                String validateCode4Login = ValidateCodeUtils.
                        generateValidateCode4String(6);
                SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE
                        ,telephone,validateCode4Login);
                jedisPool.getResource().setex(
                        telephone+RedisMessageConstant.SENDTYPE_LOGIN,
                        60*60*5,validateCode4Login);

                return new Result(true,
                        MessageConstant.SEND_VALIDATECODE_SUCCESS);
            } catch (ClientException e) {
                e.printStackTrace();
                return new Result(false,
                        MessageConstant.SEND_VALIDATECODE_FAIL);
            }
        }
        return new Result(false,
                MessageConstant.SEND_VALIDATECODE_FAIL);

    }
}
